package com.oneplatform.organisation.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesuite.common.util.BeanUtils;
import com.jeesuite.security.client.LoginContext;
import com.jeesuite.springweb.model.WrapperResponse;
import com.oneplatform.base.exception.AssertUtil;
import com.oneplatform.base.model.TreeModel;
import com.oneplatform.organisation.dao.entity.CompanyEntity;
import com.oneplatform.organisation.dto.param.CompanyParam;
import com.oneplatform.organisation.service.CompanyService;

import io.swagger.annotations.ApiOperation;

/**
 * generated by www.jeesuite.com
 */
@Controller
@RequestMapping("/company")
public class CompanyController {

	private @Autowired CompanyService companyService;

	@ApiOperation(value = "组织架构")
	@RequestMapping(value = "structure", method = RequestMethod.GET)
	public @ResponseBody WrapperResponse<List<TreeModel>> getAllStructure() {
		TreeModel root = companyService.findStructureTree();
		return new WrapperResponse<>(Arrays.asList(root));
	}

	@ApiOperation(value = "按id查询")
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public @ResponseBody WrapperResponse<CompanyEntity> getById(@PathVariable("id") int id) {
		CompanyEntity entity = companyService.findCompanyById(id);
		return new WrapperResponse<>(entity);
	}

	@ApiOperation(value = "保存总公司信息")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public @ResponseBody WrapperResponse<String> addCompany(@RequestBody CompanyParam param) {
		if(param.getBranch()){
			AssertUtil.notNull(companyService.findHeadCompany(),"请先保存总公司信息");
		}
		CompanyEntity entity = BeanUtils.copy(param, CompanyEntity.class);
		if(param.getId() == null || param.getId() == 0){
			entity.setCreatedAt(new Date());
			entity.setCreatedBy(LoginContext.getIntFormatUserId());
			companyService.addCompany(entity);
		}else{
			entity.setUpdatedAt(new Date());
			entity.setUpdatedBy(LoginContext.getIntFormatUserId());
			companyService.updateCompany(entity);
		}
		

		return new WrapperResponse<>();
	}

	@ApiOperation(value = "删除子公司")
	@RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
	public @ResponseBody WrapperResponse<String> deleteCompany(@PathVariable("id") int id) {
		companyService.deleteCompany(id);
		return new WrapperResponse<>();
	}

}
